package com.nuo.backend.modules.security.config;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nuo.backend.common.utils.JwtUtils;
import com.nuo.backend.common.utils.R;
import com.nuo.backend.modules.security.entity.SecUserEntity;
import com.nuo.backend.modules.security.service.SecUserService;
import com.nuo.backend.modules.security.service.SecUserTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {


	@Autowired
	JwtUtils jwtUtils;

	@Autowired
    SecUserService secUserService;

	@Autowired
	SecUserTokenService secUserTokenService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {

		SecUserEntity user= secUserService.getOne(new LambdaQueryWrapper<SecUserEntity>().eq(SecUserEntity::getUsername,authentication.getName()));
		response.setContentType("application/json;charset=UTF-8");
		ServletOutputStream outputStream = response.getOutputStream();

		// TODO session 存用户信息
		request.getSession().setAttribute("secUserId", user.getUserId());
		log.info("login success sessionId: " + request.getSession().getId());

		// TODO 生成 jwt
		Map<String, Object> map = jwtUtils.generateTokenMap(authentication.getName());
		String jwt = (String) map.get(jwtUtils.getHeader());

		// TODO 放置MySQL
		// secUserTokenService.saveToken(user.getUserId(), jwt, (Date) map.get("curDate"), (Date) map.get("expireDate"));

		// TODO 放置请求头
		response.setHeader(jwtUtils.getHeader(), jwt);

		// TODO 放置请求体
		outputStream.write(JSONUtil.toJsonStr(R.ok("登陆成功...").put("id", user.getUserId()).put("username", user.getUsername()).put(jwtUtils.getHeader(), jwt)).getBytes(StandardCharsets.UTF_8));

		outputStream.flush();
		outputStream.close();
	}

}
